package parser

import (
	"regexp"
	"spider/crawler/engine"
	"spider/crawler/model"
	"strconv"
)

// 用户解析器

// const ageRe = `<td><span class="label">年龄:</span>([\d]+)</td>`
var ageRe = regexp.MustCompile(`<td><span class="label">年龄:</span>([\d]+)岁</td>`)
var marriageRe = regexp.MustCompile(`<td><span class="label">婚况:</span>([^<]+)</td>`)

func ParseProfile(contents []byte, name string) engine.ParseResult {
	profile := model.Profile{}
	// 年纪 转成整数
	age, err := strconv.Atoi(extractString(contents, ageRe))
	if err != nil {
		profile.Age = age
	}
	// 婚况
	marriage := extractString(contents, marriageRe)
	profile.Marriage = marriage
	// 其它字段 类似

	profile.Name = name

	result := engine.ParseResult{
		Items: []interface{}{profile},
	}
	return result
}

func extractString(contents []byte, re *regexp.Regexp) string {
	match := re.FindSubmatch(contents)

	if len(match) >= 2 {
		return string(match[1])
	} else {
		return ""
	}
}
